package com.xuecheng.service.impl;

import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.feignclient.MediaServiceClient;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.service.LearningService;
import com.xuecheng.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class LearningServiceImpl implements LearningService {
    @Autowired
    private ContentServiceClient contentServiceClient;
    @Autowired
    private MyCourseTablesService myCourseTablesService;
    @Autowired
    private MediaServiceClient mediaServiceClient;

    @Override
    public RestResponse<String> getVideo(String userId,Long courseId,Long teachplanId, String mediaId) {
        //查询课程信息 查询的是我的课程表的信息 用来判断是否有学习的资格
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        if(coursepublish==null){
            XueChengPlusException.cast("课程信息不存在");
        }
        //校验学习资格
        //判断试学规则，远程调用内容管理服务，查询教学计划teachplan
//        Teachplan teachplan = contentServiceClient.getTeachplan(teachplanId);
//        if(teachplan == null){
//            XueChengPlusException.cast("访问的课程计划的id在课程计划表不存在");
//        }
//        //isPreview字段为1表示支持试学，返回课程url
//        if ("1".equals(teachplan.getIsPreview())) {
//            //mediaServiceClient.getPlayUrlByMediaId(mediaId);本来返回的就是RestResponse
//            return mediaServiceClient.getPlayUrlByMediaId(mediaId);
//        }
        //如果登录
        if(StringUtils.isNotEmpty(userId)){
            //判断是否选课，根据选课情况判断学习资格
            XcCourseTablesDto xcCourseTablesDto = myCourseTablesService.getLearningStatus(userId, courseId);
            //学习资格状态 [{"code":"702001","desc":"正常学习"},{"code":"702002","desc":"没有选课或选课后没有支付"},{"code":"702003","desc":"已过期需要申请续期或重新支付"}]
            String learnStatus = xcCourseTablesDto.getLearnStatus();
            if(learnStatus.equals("702002")){
                return RestResponse.validfail("没有选课或选课后没有支付");
            }else if(learnStatus.equals("702003")){
                return RestResponse.validfail("您的选课已过期需要申请续期或重新支付");
            }else {
                //mediaServiceClient.getPlayUrlByMediaId(mediaId);本来返回的就是RestResponse
                return mediaServiceClient.getPlayUrlByMediaId(mediaId);
            }
        }
        //未登录或未选课判断是否收费
        String charge = coursepublish.getCharge();
        if(charge.equals("201000")){//免费可以正常学习
            return mediaServiceClient.getPlayUrlByMediaId(mediaId);
        }
        return RestResponse.validfail("请购买课程后继续学习");
    }
}
